<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  users
 */

class m_users_actions_block_FormUsersAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$formProvider = f_form_Provider::getInstance();
		
		$formProvider->setDocumentName("users")
		             ->setModuleName("users")
		             ->setFormName("FormUsers");
		
		$users = m_users_documents_User::createNew();
		
		$values = $formProvider->getParams();
		if($formProvider->isSubmitted())
		{
			if($formProvider->isValid())
			{
                $key = m_backoffice_services_BackOfficeService::getKey();
				$users
					->setAuthor($this->getUser()->getlogin())
					->setLabel($values['formValues']['login'])
					->setLogin($values['formValues']['login'])
					->setPassword(md5($values['formValues']['password'].$key))
					->setFirstname($values['formValues']['prenom'])
					->setLastname($values['formValues']['nom'])
					->setEmail($values['formValues']['mail'])
					->save();
					
				$group = $this->getDocumentProvider()->getByUniqueId($values['formValues']['group']);
				$group->addUser($users)->save();
				
				if($this->getUserContext()->hasRight("users_Edit"))
                {
                    $this->closeModalAndRedirect($users->getEditUrl());
                }

                $this->closeModalAndRefresh();
			}
			else
			{
				$values['errors'] = $formProvider->getErrors();
			}
		}
 			
		// Retrieve special fields
		$specialFields = $this->getGroups();
		if($specialFields != null)
		{
			$values['relatedDocs'] = $specialFields;
		}
		
		$values["users"] = $users;
		$values["href"] = $this->getRequestParameter("href");
		$values["docId"] = $this->getRequestParameter("docId");
		$this->setModel($values);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo","users_Add"));
	}
 	
	private function getGroups($lang = null)
	{
        if(is_null($lang))
        {
            $lang = $this->getContextLang();
        }

        $rootNode = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode('users');

        $groups = f_relation_Manager::getInstance()->getChildsByDocTypeRecursive($rootNode->getUniqueId(), array('modules_users/group'), $lang);

        return $groups;
	}
}	